package com.dream.cgomall.service.impl;

import com.dream.cgomall.dao.*;
import com.dream.cgomall.dto.*;
import com.dream.cgomall.entity.CgoAdmin;
import com.dream.cgomall.entity.CgoAdminWallet;
import com.dream.cgomall.entity.CgoRole;
import com.dream.cgomall.service.CgoAdminService;
import com.dream.cgomall.service.ServiceResult;
import com.dream.cgomallcore.util.NumRandom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (CgoAdmin)表服务实现类
 *
 * @author makejava
 * @since 2021-07-01 23:59:56
 */
@Service("cgoAdminService")
public class CgoAdminServiceImpl implements CgoAdminService {
    private static final String BEFORE_KEY = "SMS::CODE:";

    @Autowired(required = false)
    CgoAdminSupriseDao cgoAdminSupriseDao;
    @Autowired(required = false)
    private CgoAdminDao cgoAdminDao;
    @Autowired(required = false)
    private CgoRoleDao cgoRoleDao;
    @Autowired(required = false)
    CgoAdminHistoryDao cgoAdminHistoryDao;
    @Autowired(required = false)
    CgoAdminAttentionDao cgoAdminAttentionDao;
    @Autowired(required = false)
    CgoAdminMylikeDao cgoAdminMylikeDao;
    @Autowired(required = false)
    CgoOrderDao cgoOrderDao;
    @Autowired(required = false)
    private CgoAdminWalletDao cgoAdminWalletDao;

    @Autowired(required = false)
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 注册并登录
     *
     * @param cgoAdmin
     * @param code
     * @return 返回前端 id-token
     */
    @Transactional
    @Override
    public ServiceResult<UserDTO> singUp(CgoAdmin cgoAdmin, String code) {
        if (cgoAdminDao.selectPhone(cgoAdmin.getPhone()) > 0) {
            return ServiceResult.HaveNotPhone();
        }
        String search = BEFORE_KEY + cgoAdmin.getPhone();
        String Rcode = (String) redisTemplate.opsForValue().get(search);
        if (Rcode == null || Rcode == "") {
            return ServiceResult.badResult("验证码有误");
        }

        //加密
        cgoAdmin.setPassword(bCryptPasswordEncoder.encode(cgoAdmin.getPassword()));

        cgoAdminDao.insert(cgoAdmin);
        UserDTO userDTO = new UserDTO(cgoAdmin.getId(), cgoAdmin.getPhone(), cgoAdmin.getUsername());
        String token = NumRandom.createUUID();
        userDTO.setToken(token);
        redisTemplate.opsForValue().set(token, userDTO.getId(), 30, TimeUnit.MINUTES);
        // CgoRole role=new CgoRole();
        // role.setUserId(cgoAdmin.getId());
        // role.setRole("USER");
        // role.setDesc("普通用户权限");
        // cgoRoleDao.insert(role);
        // CgoAdminWallet wallet=new CgoAdminWallet();
        // wallet.setUserId(cgoAdmin.getId());
        // cgoAdminWalletDao.insertInitByUserId(wallet);
        return ServiceResult.of(userDTO);
    }

    /**
     * 通过ID查询单条数据
     *
     * @return 实例对象
     */
    @Transactional
    @Override
    public ServiceResult<UserDTO> Login(String phone, String password) {
        CgoAdmin cgoAdmin = cgoAdminDao.queryByPhoneAndpassword(phone, password);
        if (!bCryptPasswordEncoder.matches(password, cgoAdmin.getPassword())) {
            return ServiceResult.notFound();
        }
        cgoAdminDao.updateTime(cgoAdmin.getId());
        UserDTO userDTO = new UserDTO(cgoAdmin.getId(), cgoAdmin.getPhone(), cgoAdmin.getUsername());
        String token = NumRandom.createUUID();
        userDTO.setToken(token);
        redisTemplate.opsForValue().set(token, userDTO.getId(), 50, TimeUnit.MINUTES);
        return ServiceResult.of(userDTO);
    }

    /**
     * 手机短信登录
     *
     * @param phone 手机登录
     * @return 返回前端id-token
     */
    @Transactional
    @Override
    public ServiceResult SmsLogin(String phone) {
        CgoAdmin cgoAdmin = cgoAdminDao.queryByPhone(phone);
        if (cgoAdmin == null) {
            return ServiceResult.notFound();
        }
        cgoAdminDao.updateTime(cgoAdmin.getId());
        UserDTO userDTO = new UserDTO(cgoAdmin.getId(), cgoAdmin.getPhone(), cgoAdmin.getUsername());
        String token = NumRandom.createUUID();
        userDTO.setToken(token);
        redisTemplate.opsForValue().set(token, userDTO.getId(), 30, TimeUnit.MINUTES);
        return ServiceResult.of(userDTO);
    }

    @Override
    public ServiceResult chengePhone(String phone) {
        if (cgoAdminDao.updateByPhone(phone) > 0) {
            return ServiceResult.success();
        }
        return ServiceResult.badResult("该手机号已被注册");
    }


    @Override
    public ServiceResult loadMyPage(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("history", cgoAdminHistoryDao.selectCount(id));
        map.put("like", cgoAdminMylikeDao.selectCount(id));
        map.put("attention", cgoAdminAttentionDao.selectCount(id));
        map.put("base", cgoAdminDao.selectUserAll(id));
        map.put("order", cgoOrderDao.selectGoodsCountByStatus(id));
        map.put("wallet", cgoAdminWalletDao.selectWalletByUserId(id));
        map.put("suprise", cgoAdminSupriseDao.selectCountByUserId(id));
        return ServiceResult.of(map);
    }

    @Override
    public ServiceResult getUserinfo(Integer id) {
        CgoAdmin cgoAdmin = cgoAdminDao.selectUserinfo(id);
        return ServiceResult.of(cgoAdmin);
    }

    @Override
    public ServiceResult updateUserinfo(CgoAdmin cgoAdmin) {
        try {
            int result = cgoAdminDao.updateUserinfo(cgoAdmin);
            if (result <= 0) {
                return ServiceResult.badResult("修改失败");
            }
        } catch (RuntimeException e) {
            return ServiceResult.badResult("修改失败");
        }
        return ServiceResult.success();
    }

}
